package com.xyy.saas.payment.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.api.OpenAccountApi;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.cores.vo.UserInfoVo;
import com.xyy.saas.payment.merchant.core.dto.UserInfoDto;
import com.xyy.saas.payment.merchant.core.service.AccountModifyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Stream;

/**
 * @author wangzeqi
 */
@Slf4j
@Service(version = "1.0.0")
@RequiredArgsConstructor
public class OpenAccountApiImpl implements OpenAccountApi {

    private final AccountModifyService accountModifyService;

    @Override
    public ResultVO updateUserInfoAndPinganAccount(UserInfoVo userInfoVo) {
        log.info("OpenAccountApiImpl updateUserInfoAndPinganAccount param:{}", JSON.toJSONString(userInfoVo));
        try {
            checkUpdateUserInfoParam(userInfoVo);
            UserInfoDto userInfoDto = convertToDTO(userInfoVo);
            accountModifyService.updateUserInfoAndPinganAccount(userInfoDto);
            return ResultVO.createSuccess();
        } catch (PaymentException e) {
            log.error("OpenAccountApiImpl updateUserInfoAndPinganAccount error, {}-{}", userInfoVo.getBusinessUserId(), e.getErrMsg(), e);
            ResultVO resultVO = new ResultVO<>();
            resultVO.setCode(e.getErrCode());
            resultVO.setMsg(e.getErrMsg());
            return resultVO;
        } catch (Exception e) {
            log.error("OpenAccountApiImpl updateUserInfoAndPinganAccount error, {}-{}", userInfoVo.getBusinessUserId(), e.getMessage(), e);
            return ResultVO.createError(e.getMessage());
        }
    }

    private UserInfoDto convertToDTO(UserInfoVo userInfoVo) {
        return new UserInfoDto()
                .setIdNo(userInfoVo.getIdNo())
                .setName(userInfoVo.getName())
                .setBusinessUserId(userInfoVo.getBusinessUserId())
                .setBusinessUserName(userInfoVo.getBusinessUserName())
                .setBusinessIdType(userInfoVo.getBusinessIdType());
    }

    private void checkUpdateUserInfoParam(UserInfoVo userInfoVo) throws PaymentException {
        boolean paramsValid = Stream.of(userInfoVo.getBusinessUserId(), userInfoVo.getBusinessIdType(), userInfoVo.getBusinessUserName())
                .allMatch(StringUtils::isNotBlank);
        if (!paramsValid) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR);
        }
    }

}
